const express = require('express');
const router = express.Router();
// 引入jwt token工具
const jwtUtil = require('../utils/token/jwtUtil');
const dbUtil = require('../models/db/dbUtil');
const multipart = require('connect-multiparty');//解决：body-parser 并不支持 contentType: multipart/form-data 的格式类型，也就是不支持 formData 格式
const resultFormat = require('../utils/resultFormat');//统一返回格式化
const multipartyMiddleware = multipart();

router.use("/",async function (req, res, next) {
    if (req.url !== '/login' &&  req.url !== '/register') {
        let token = req.headers["access-token"];
        if(!token){
            res.send({status: 403, msg: '没有token授权'});
            return;
        }
        let verinfyInfo = await jwtUtil.verifyToken(token);
        // 如果考验通过就next，否则就返回登陆信息不正确
        if (verinfyInfo.status !== 200) {
            res.send(verinfyInfo);
            return;
        }
    }
    next();
});

/**
 * @api {get} /users/verifyToken 验证token
 * @apiDescription 验证token
 * @apiName verifyToken
 * @apiGroup users
 * @apiHeader {String} access-token 用户token.
 * @apiVersion 1.0.0
 */
router.get('/verifyToken',  async function(req, res, next) {
    res.send({status:200,msg:'token验证成功'});
});

router.get('/getUseInfo',  async function(req, res, next) {
    //TODO 查询用户信息表
    res.send({status:200,msg:'获得用户信息'});
});
/**
 * @api {post} /users/login 登录
 * @apiDescription 登录
 * @apiName login
 * @apiGroup users
 * @apiParam {string} userName=cpc 用户名
 * @apiParam {string[6...12]} password=123456 密码
 * @apiVersion 1.0.0
 */
router.post('/login', async function(req, res, next) {
    let {userName,password} = req.body;
    //参数验证模块封装
    let [error1,count] = await dbUtil.countDocuments("user_info",{userName,password});
    if(error1){
        res.status(500).send({status:500,msg:'服务器内部错误'});
    }
    if(count === 0){
        res.send({status:403,msg:'账号或者密码错误'});
        return;
    }
    // 将用户id传入并生成token
    let [err,token] = await jwtUtil.generateToken({userName});
    if(err){
        res.status(500).send({status:500,msg:'构建token出错'});
    }
    let [error,updateSuccess] = await dbUtil.updateOne("user_info",{userName,password},{token});
    if(error || (updateSuccess.ok !== 1)){
        res.status(500).send({status:500,msg:'服务器出错了'});
    }
    res.send({status:200,msg:'登录成功',token:token});
});
/**
 * @api {post} /users/register 注册
 * @apiDescription 注册
 * @apiName register
 * @apiGroup users
 * @apiParam {string} userName=cpc 用户名
 * @apiParam {string[6...12]} password=123456 密码
 * @apiVersion 1.0.0
 */
router.post('/register', async function(req, res, next) {
    let {userName, password} = req.body;
    let [findError,count] = await dbUtil.countDocuments("user_info",{userName});
    console.log(findError,count)
    if(findError){
        res.status(500).send({status:403,msg:'用户查询错误'});
        return
    }
    if(count === 1){
        res.send({status:403,msg:'该用户已存在'});
        return;
    }else if(count>1){
        res.status(500).send({status:500,msg:'注册失败，服务器内部错误'});
    }
    let [error,saveOk] = await dbUtil.save("user_info",{userName,password});
    if(error){
        res.status(500).send({status:500,msg:'注册失败'});
        return;
    }
     res.send({status:200,msg:'注册成功'});
});

module.exports = router;
